<template>
  <el-card class="m-dept-side">
    <div class="title">科室列表</div>
    <el-input v-model="filterText" placeholder="输入关键字进行过滤" class="filter-search" />
    <div class="filter-tree">
      <el-scrollbar class="scrollbar">
        <el-tree
          ref="treeRef"
          :data="tableData"
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          node-key="id"
          :highlight-current="true"
          :current-node-key="currentKey"
          @node-click="bindNode"
        />
      </el-scrollbar>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { onBeforeMount, onMounted, ref, watch } from 'vue'
import { ElTree } from 'element-plus'
import { deptData } from '@/mock/system'
import { selectListArray } from '@/api/admin'
import { format } from 'echarts'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const tableData = ref<Tree[]>()
interface Tree {
  id: string
  name: string
  children?: Tree[]
}

const filterText = ref('')
const treeRef = ref()

const defaultProps = {
  children: 'children',
  label: 'name',
}

const currentKey = ref(0)

// 监听输入
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

// 搜索
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}

const getList = () => {
  selectListArray({ platform_id: route.query.id, selectFields: 'id,name' }).then((res) => {
    if (res.code == 200) {
      let allObj = { id: 0, name: '全部' }
      tableData.value = [allObj, ...res.data]
      if (route.query.deptId) currentKey.value = route.query.deptId
    }
  })
}

if (route.query.id) {
  getList()
}

const emit = defineEmits<{ (event: 'node', id: number): void }>()

const bindNode = (node) => {
  router.replace(`/hospital/staff?id=${route.query.id}&deptId=${node.id}`)
  emit('node', node.id)
}
</script>

<style lang="scss" scoped>
@import '../index.scss';
</style>
